package controller

import (
	"encoding/json"
	"io"
	"net/http"

	"github.com/gin-gonic/gin"
)

func GetOpenid(c *gin.Context) {
	// 从请求中获取参数
	code := c.Query("code")
	if code == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "code is required"})
		return
	}

	// 获取渠道参数
	channel := c.Param("channel")
	if channel == "" {
		c.JSON(http.StatusBadRequest, gin.H{"error": "channel is required"})
		return
	}

	var (
		appID     string
		appSecret string
	)

	// 根据渠道参数调整逻辑
	switch channel {
	case "wx":
		// 微信渠道
		appID = "your_wx_app_id"
		appSecret = "your_wx_app_secret"
	case "ks":
		// 快手渠道
		appID = "your_ks_app_id"
		appSecret = "your_ks_app_secret"
	case "tt":
		// 抖音渠道
		appID = "your_tt_app_id"
		appSecret = "your_tt_app_secret"
	default:
		c.JSON(http.StatusBadRequest, gin.H{"error": "unsupported channel"})
		return
	}

	// 构造 API 请求
	apiURL := "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" + appID +
		"&secret=" + appSecret +
		"&code=" + code +
		"&grant_type=authorization_code"

	// 发起 HTTP 请求
	resp, err := http.Get(apiURL)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to call API"})
		return
	}
	defer resp.Body.Close()

	// 读取响应内容
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to read response"})
		return
	}

	// 解析响应内容
	var result map[string]interface{}
	if err := json.Unmarshal(body, &result); err != nil {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "failed to parse response"})
		return
	}

	// 检查是否有错误
	if _, ok := result["errcode"]; ok {
		c.JSON(http.StatusInternalServerError, gin.H{"error": result["errmsg"]})
		return
	}

	// 提取 OpenID
	openID := result["openid"].(string)
	if openID == "" {
		c.JSON(http.StatusInternalServerError, gin.H{"error": "OpenID not found"})
		return
	}

	// 返回 OpenID 和渠道信息
	c.JSON(http.StatusOK, gin.H{
		"openid":  openID,
		"channel": channel,
	})
}

func GetClientConfigVersion(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": gin.H{
			"version":       "1.0.0",
			"oss_conf_root": "confs/test-server/",
		},
	})
}

func GetClientConfigFilePath(c *gin.Context) {
	c.JSON(http.StatusOK, gin.H{
		"code": 0,
		"msg":  "success",
		"data": gin.H{
			"file_path": "https://shilaike.oss-cn-beijing.aliyuncs.com/guandan/",
		},
	})
}
